﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Model;

namespace DevelopTool.Forms.CommonForms
{
    /// <summary>
    /// 数据选择窗口
    /// </summary>
    public partial class DataSelectForm : BaseUIForm
    {
        /// <summary>
        /// 已选择的值
        /// </summary>
        public DataTable SelectValues
        {
            get
            {
                return selectValues;
            }
        }

        #region 私有属性    


        /// <summary>
        /// 数据列
        /// </summary>
        private List<DataGridColumn> dataGridColumns;


        /// <summary>
        /// 需要选择的数据集
        /// </summary>
        private DataTable dataTable;

        /// <summary>
        /// 已选择的数据集
        /// </summary>
        private DataTable selectValues;

        /// <summary>
        /// DataGridView筛选下拉框
        /// </summary>
        private DataGridViewFilterForm dgvFilterForm;


        #endregion 私有属性


        public DataSelectForm(string windowTitleText, List<DataGridColumn> dataGridColumns, DataTable dataTable, DataTable selectValues)
        {
            InitializeComponent();
            this.Text = windowTitleText;

            this.dataGridColumns = dataGridColumns;

            this.dataTable = dataTable;

            this.selectValues = selectValues;
        }


        private void DataSelectForm_Load(object sender, EventArgs e)
        {
            #region DataGridView样式设置
            this.dataGridView.EnableHeadersVisualStyles = false;
            this.dataGridView.ShowCellToolTips = false;
            this.dataGridView.AllowUserToAddRows = false;
            // dgv.AllowUserToDeleteRows = false;
            this.dataGridView.AllowUserToOrderColumns = true;
            //  dgv.EnableHeadersVisualStyles = false;
            this.dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            this.dataGridView.RowHeadersVisible = true;

            this.dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;

            #endregion DataGridView样式设置

            if(!this.dataGridColumns.Exists(it => it.ColumnName == "CheckBox" && it.ColumnText == "选择"))
                this.dataGridColumns.Insert(0, new DataGridColumn("CheckBox") { ColumnText = "选择", Width = 50 });


            if (!this.dataTable.HasColumn("CheckBox"))
            {
                this.dataTable.Columns.Add("CheckBox", typeof(bool));
                dataTable.BatchSetValue("CheckBox", false);
            }

            if (this.selectValues == null || this.selectValues.Columns.Count <= 0)
            {
                this.selectValues = this.dataTable.Clone();//同步两个dataTable的结构
            }
            else
            {
                for (int i = 0; i < this.dataTable.Rows.Count; i++)
                {
                    bool exist = false;

                    foreach (DataColumn dataColumn in this.dataTable.Columns)
                    {
                        if (dataColumn.ColumnName == "CheckBox") continue;
                       
                        if (this.selectValues.Select().Any(it => it[dataColumn.ColumnName].ToString() == this.dataTable.Rows[i][dataColumn.ColumnName].ToString()))
                        {
                            exist = true; //比较每一列的值是否相同，如果相同那就说明是选中的
                        }
                        else
                        {
                            exist = false;//只要有一个列的值不相等，那就表示这一行不是选中的
                            break;
                        }
                    }

                    this.dataTable.Rows[i]["CheckBox"] = exist;
                }
            }

            this.dataGridView.AddCheckBoxColumn("选择", "CheckBox", readOnly: false);//新增checkbox选择列

            this.dataGridView.DataSource = DataGridViewHelper.BindingSource(this.dataTable);

            this.dgvFilterForm = new DataGridViewFilterForm(this.uiPanel1, dataGridView.Columns);

            ThemHelper.SetSystemThem(this);

            DataGridViewHelper.SetDataGridViewColumnWidth(this.dataGridView,this.dataGridColumns);
        }


        #region dataGridView


        private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.AddColumnHeader(dataGridView, e);
        }


        private void dataGridView_DataSourceChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewColumn column in this.dataGridView.Columns)
            {
                if (column.HeaderText != "选择")
                    column.ReadOnly = true;
            }

            DataGridViewHelper.SetDataGridViewColumnInfo(dataGridView, dataGridColumns);

           // SetDgvSelectRowColor();

        }


        private void dataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)//判断点的是不是左键
            {
                if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
                var selectRow = this.dataGridView.Rows[e.RowIndex];//选定的行
                if (Convert.ToBoolean(selectRow.Cells["选择"].Value) == true)
                {
                    selectRow.Cells["选择"].Value = false;//取消选择
                }
                else
                {
                    selectRow.Cells["选择"].Value = true;//选择
                }
            }
        }


        private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
          //  SetDgvSelectRowColor();
        }


        private void dataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGridView.IsCurrentCellDirty)
            {
                dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void dataGridView_SizeChanged(object sender,EventArgs e)
        {
            DataGridViewHelper.SetDataGridViewColumnWidth(this.dataGridView,this.dataGridColumns);
        }

        #endregion dataGridView


        private void TextBoxKeyword_TextChanged(object sender, EventArgs e)
        {
            dataGridView.DataSource = DataGridViewHelper.BindingSource(this.dataTable, this.dgvFilterForm.GetFilter(this.TextBoxKeyword.Text));
        }

        private void TextBoxKeyword_ButtonClick(object sender, EventArgs e)
        {
            this.dgvFilterForm.ShowForm(this.TextBoxKeyword);
        }


        /// <summary>
        /// 全选框选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiCheckBoxAll_MouseClick(object sender, MouseEventArgs e)
        {
            if (uiCheckBoxAll.Checked)
            {
                foreach (DataGridViewRow row in dataGridView.Rows)
                {
                    row.Cells["选择"].Value = true;
                }
            }
            else
            {
                foreach (DataGridViewRow row in dataGridView.Rows)
                {
                    row.Cells["选择"].Value = false;
                }
            }
        }


        /// <summary>
        /// 取消选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancelCheck_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                row.Cells["选择"].Value = false;
            }
            this.uiCheckBoxAll.Checked = false;
        }


        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            this.selectValues.Clear();

            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                if (Convert.ToBoolean(row.Cells["选择"].Value) == true)
                {
                    DataRow newRow = this.selectValues.NewRow();
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.OwningColumn.HeaderText == "选择") continue;

                        newRow[cell.OwningColumn.DataPropertyName] = row.Cells[cell.OwningColumn.DataPropertyName].Value;
                    }
                    this.selectValues.Rows.Add(newRow);
                }
            }

            this.DialogResult = DialogResult.OK;
        }


        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        
    }
}
